package com.education.wisdom.controller.app;

import com.education.common.pojo.SysUserOther;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.DateLiuUtil;
import com.education.wisdom.feign.UserFeign;
import com.education.wisdom.pojo.CurrencyRecord;
import com.education.wisdom.pojo.LessonMenu;
import com.education.wisdom.pojo.LessonResources;
import com.education.wisdom.pojo.LessonresourceUserBuy;
import com.education.wisdom.service.ICurrencyRecordService;
import com.education.wisdom.service.LessonMenuService;
import com.education.wisdom.service.LessonResourcesService;
import com.education.wisdom.service.LessonresourceUserBuyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/appRes")
public class AppResController {

    @Autowired
    private LessonResourcesService resourcesService;
    @Autowired
    private LessonMenuService menuService;
    @Autowired
    private LessonresourceUserBuyService userBuyService;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private ICurrencyRecordService recordService;

    //判断类型
    public void judgeType(LessonResources lessonResource) {
        //1 文档 4 图片 5 视频
        if (lessonResource.getTypeId() == 1) lessonResource.setType("文档");
        else if (lessonResource.getTypeId() == 4) lessonResource.setType("图片");
        else if (lessonResource.getTypeId() == 5) lessonResource.setType("视频");
    }

    /**
     * 共享资源-全部专业列表
     *
     * @param menu
     * @return
     */
    @GetMapping("/menuList")
    public ApiReturnObject menuList(LessonMenu menu) {
        List<LessonMenu> arrayList = Lists.newArrayList();
        LessonMenu lessonMenu = new LessonMenu();
        lessonMenu.setName("全部专业");
        arrayList.add(lessonMenu);
        List<LessonMenu> lessonMenus = menuService.selectLessonMenuList(menu);
        if (lessonMenus.size() > 0) arrayList.addAll(lessonMenus);
        return new ApiReturnObject("200", "查询成功", arrayList);
    }

    /**
     * 共享资源-资源列表
     * 专业  lessonId   分类 typeId
     *
     * @param resources
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public ApiReturnObject list(LessonResources resources, Integer pageNum, Integer pageSize) {
        //设置分页
        if (pageNum != null && pageSize != null) PageHelper.startPage(pageNum, pageSize);
        //查询资源数据
        List<LessonResources> lessonResources = resourcesService.selectLessonResourcesList(resources);
        //查询用户已购买资源
        List<Integer> resIds = userBuyService.selectLessonresourceUserBuyListOther(resources.getUserId());
        //判断该用户是否已经购买
        for (LessonResources lessonResource : lessonResources) {
            if (resIds.contains(lessonResource.getId())) lessonResource.setIsRed(1);
            else lessonResource.setIsRed(0);
            if (lessonResource.getRCreateuser().equals(resources.getUserId())) lessonResource.setIsRed(1);
            //1 文档 4 图片 5 视频 设置type
            judgeType(lessonResource);
        }
        PageInfo<LessonResources> pageInfo = new PageInfo<>(lessonResources);
        return new ApiReturnObject("200", "查询成功", pageInfo);
    }

    /**
     * 共享资源详情-(讲师详情、课件简介、全部资源)
     *
     * @param id     资源id
     * @param userId 当前用户id
     * @return
     */
    @GetMapping("/selectOne")
    public ApiReturnObject selectOne(Integer id, Integer userId) {
        if (id != null) {
            //名称 价格 老师头像 老师名字 资源路径
            LessonResources lessonResources = resourcesService.selectLessonResourcesByIdOther(id);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd");
            String format = simpleDateFormat.format(lessonResources.getCreateTime());
            lessonResources.setCreateTimeStr(format);
            //1 文档 4 图片 5 视频 设置type
            judgeType(lessonResources);
            //老师上传课件数
            Integer count = resourcesService.selectLessonResourcesCount(lessonResources.getRCreateuser());
            lessonResources.setCount(count);
            //判断是否已经购买
            LessonresourceUserBuy userBuy = new LessonresourceUserBuy();
            userBuy.setUserId(userId);
            userBuy.setResourceId(id);
            List<LessonresourceUserBuy> lessonresourceUserBuys = userBuyService.selectLessonresourceUserBuyList(userBuy);
            //是否购买
            if (lessonresourceUserBuys.size() > 0) lessonResources.setIsRed(1);
            else lessonResources.setIsRed(0);
            if (lessonResources.getRCreateuser().equals(userId)) lessonResources.setIsRed(1);
            //资源集合
            List<String> rList = Arrays.asList(lessonResources.getRUrl().split(","));
            if (rList.size() > 0) lessonResources.setResList(rList);
            else lessonResources.setResList(Lists.newArrayList());
            return new ApiReturnObject("200", "查询成功", lessonResources);
        }
        return new ApiReturnObject("201", "缺少参数id", "");
    }

    /**
     * 订单号生成   20200718112629527
     */
    public static String nextItemNo() {
        LocalDateTime dateTime = LocalDateTime.now();
        return DateLiuUtil.getOtherFormatterLocalDateTime(dateTime);
    }

    /**
     * 学生APP端购买备课共享资源
     */
    @PostMapping("/addBatch")
    @Transactional
    public ApiReturnObject addBatch(LessonResources lessonResource) {
        //获取课程
        LessonResources lessonResources = resourcesService.selectLessonResourcesById(lessonResource.getId());
        //获取用户账户表
        SysUserOther sysUserOther = userFeign.selectOnePCF(lessonResource.getUserId() + "");
        //获取到达人币
        BigDecimal currency = sysUserOther.getPrice();
        //获取课程价格
        Integer price = lessonResources.getPrice();
        Map<String, Object> map = new HashMap<>();
        map.put("userId", lessonResource.getUserId());
        map.put("catalogId", lessonResource.getId());
        LessonresourceUserBuy userBuy = new LessonresourceUserBuy();
        userBuy.setUserId(lessonResource.getUserId());
        userBuy.setResourceId(lessonResource.getId());
        List<LessonresourceUserBuy> lessonresourceUserBuys = userBuyService.selectLessonresourceUserBuyList(userBuy);
        if (lessonresourceUserBuys.size() != 1) {
            //if (currency >= price) {
            if (currency.compareTo(new BigDecimal(price)) >= 0) {
                Map<String, Object> mp = new HashMap<>();
                mp.put("id", lessonResource.getUserId());
                //mp.put("price", currency - price);
                mp.put("price", currency.subtract(new BigDecimal(price)));
                userFeign.updataByUserId(mp);
                //往备课资源购买表 添加资源
                userBuy.setCreatetime(new Date());
                userBuy.setDeflag("1");
                userBuyService.insertLessonresourceUserBuy(userBuy);

                //jr_currency_record
                CurrencyRecord currencyRecord = new CurrencyRecord();
//                //课程id
                currencyRecord.setCatalogId(lessonResources.getId());
//                //类型
                currencyRecord.setTrxType("3");
                currencyRecord.setOrderType("2");
//                //价格
                if (0 != price) {
                    currencyRecord.setCurrency(new BigDecimal(price));
                } else {
                    currencyRecord.setCurrency(new BigDecimal(price));
                }
//                //创建时间
                currencyRecord.setCreateTime(new Date());
//                //付款时间
                currencyRecord.setEditTime(new Date());
//                //订单id
                currencyRecord.setCurrencyId(nextItemNo());
//                //status
                currencyRecord.setStatus("1");
                //备注
                currencyRecord.setRemark("备课共享资源购买");
//                //userId
                currencyRecord.setUserId(lessonResource.getUserId().toString());
//                //支付者姓名
                currencyRecord.setPayerName(sysUserOther.getSysRelname());
//                //删除标志
                currencyRecord.setDelFlag("0");
                recordService.insertCurrencyRecord(currencyRecord);
                return new ApiReturnObject("200", "购买成功", "");
            } else {
                return new ApiReturnObject("201", "账户余额不足", "");
            }
        } else {
            return new ApiReturnObject("201", "已购买", "");
        }
    }

}
